<?php
namespace core;

use Anno\Mapping\RequestMapping;
use Anno\Parser\RequestMappingParser;

class Application
{

    public static $beans = [];

    public static function init($loader)
    {
        \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
        self::loadAnnoRoute();
        self::loadAnnoBean();
        //var_dump(self::$beans);
    }

    public function run()
    {

    }

    /**
     * 加载类到Bean容器中
     */
    public static function loadAnnoBean()
    {
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        $obj = new Route();
        $re = new \ReflectionClass($obj);

        //把route类加入到容器当中，下次使用route类的时候就直接从容器调出

        $classAnnos = $reader->getClassAnnotations($re);
        foreach ($classAnnos as $classAnno){
            $beanName = $classAnno->getName();
            self::$beans[$beanName] = $re->newInstance();
        }
    }

    public static function getBean($name)
    {
        return self::$beans[$name]??'';
    }

    public static function loadAnnoRoute()
    {
        $obj = new \App\Http\Controller\HomeController();
        $re = new \ReflectionClass($obj);

        //自动加载注解类到组件当中
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();//注解组曲类
        $classAnnos = $reader->getClassAnnotations($re);
        foreach ($classAnnos as  $v){
            $routePrefix = $v->getPrefix();
        }

        $refMethods = $re->getMethods();
        foreach ($refMethods as $method){
            $methodAnno = $reader->getMethodAnnotations($method);
            foreach ($methodAnno as $item) {
                $routePath = $item->getRoute();
                (new RequestMappingParser())->parse($routePrefix, $routePath, $re->newInstance(),$method->name);
            }
        }
    }

}
